package postgresql;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class TestJDBC {
	
	private static Properties props = initProps();
	
	public static void main(String[] args) {
		
		Connection conn = null;
		try {
			
			String driverEspecific = getPropietat("rdbms.driver");
			Class.forName(driverEspecific).newInstance();
			
			conn = DriverManager
				.getConnection(
						getPropietat("rdbms.url"),
						getPropietat("rdbms.usuario"), 
						getPropietat("rdbms.pwd"));
			
			mostrarInfoMetadata(conn);
			mostrarPeliculas(conn);
			
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException e) {
			
			e.printStackTrace();
			
		} catch (SQLException e) {			
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {					
					e.printStackTrace();
				}
			}
		}
	}

	private static void mostrarPeliculas(Connection conn) {
		try {
			Statement statement = conn.createStatement();
			
			ResultSet rs = 
					statement.executeQuery("select * from pel");
			
			while(rs.next()) {
				System.out.println(
						rs.getInt("p_num") + " - " +
						rs.getString("titulo"));
			}
			
		} catch (SQLException e) {			
			e.printStackTrace();
		}
		
	}

	private static void mostrarInfoMetadata(Connection conn) {
		try {
			DatabaseMetaData dbmd = conn.getMetaData();
			
			System.out.println("Nombre driver: " + dbmd.getDriverName());
			System.out.println("Version driver: " + dbmd.getDriverVersion());
			System.out.println("Nombre del RDMBS: " + dbmd.getDatabaseProductName());
			System.out.println("Version del RDMBS: " + dbmd.getDatabaseProductVersion());
			
			System.out.println("Catalogos en el RDBMS:");
			ResultSet rs = dbmd.getCatalogs();			
			while (rs.next()) {
				System.out.println("-" + rs.getString(1));
			}			
		} catch (SQLException e) {			
			e.printStackTrace();
		}
		
	}

	private static Properties initProps() {
		 // propFileDbName --> variable que li passem com a argument al arrencar el programa
		// es crida amb un -D
		String nomPropertiesFileDb = System.getProperty("propFileDbName");
		InputStream is = 
			TestJDBC.class.getResourceAsStream("/"+nomPropertiesFileDb);
			
		props = new Properties();
		try {
			props.load(is);
			return props;
		} catch (IOException e) {			
			e.printStackTrace();
		}
		throw new RuntimeException("Error cargando fichero de propiedades de la BD!");
	}

	private static String getPropietat(String propiedad) {
		return props.getProperty(propiedad);
	}

}
